package org.elephantt.webby;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Adapter between Servlets and Webby. Sadly, because Java webapps suck, initialization occurs through servlet context
 * attributes.
 */
public class DispatcherServlet extends HttpServlet {
  private static final long serialVersionUID = 6167695773258627518L; // that HttpServlet is serializable offends me greatly. This is insane.
  private Dispatcher dispatcher;

  /**
   * Creates the dispatcher for the dispatcher servlet. Applications should override this to do anything useful.
   *
   * @param config
   */
  public Dispatcher createDispatcher(ServletConfig config) {
    return new Dispatcher(new RouteRequestMapper(), new SimpleRequestResponseFactory());
  }

  @Override
  public void init(ServletConfig config) throws ServletException {
    dispatcher = createDispatcher(config);
    if (dispatcher == null) {
      throw new ServletException("createDispatcher() must return non-null dispatcher");
    }
  }

  public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    dispatcher.dispatch((HttpServletRequest) request, (HttpServletResponse) response);
  }
}